package service;

import java.util.List;

import org.apache.log4j.Logger;
import org.jgroups.Address;

import communication.Communicator;
import communication.ParameterizedMessage;
import communication.RequestHandler;
import platform.ServiceStatusRequestHandler;
import role.Role;

public abstract class AbstractService {
	
	protected Communicator serviceBus;
	
	protected Communicator coWorkers;
	
	private boolean closed = false;
	
	
	public abstract void init() throws Exception;
	
	public void run() {
	}
	
	public void close(ParameterizedMessage message) {
	}
	
	public String getServiceName() {
		return this.getClass().getName();
	}
	
	public boolean isMaster() {
		Address masterAddress = coWorkers.getMaster();
		Address localAddress = coWorkers.getLocalAddress();
		return masterAddress.equals(localAddress);
	}
	
	public void addRole(Role role) {
		coWorkers.addRole(role);
	}
	
	protected final void startCommunication() {
		
		
		coWorkers = new Communicator(getServiceName());
		
		//serviceBus = new Communicator("SERVICE_BUS");
		//serviceBus.addRequestHandler(new StopServiceRequestHandler(this));
		//serviceBus.addRequestHandler(new ServiceStatusRequestHandler(this));
	}
	
	protected final void stopCommunication() {
		serviceBus.close();
		
		coWorkers.close();
	}
	
	protected final boolean isClosed() {
		return closed;
	}
	
	protected final void markAsClosed() {
		closed = true;
	}

}
